import React, {useState, forwardRef, useImperativeHandle, PropsWithChildren, useEffect} from "react"
import {
  Button,
  Card,
  Col,
  Table,
  Drawer,
  Form,
  Row,
  Input,
  Select,
  Divider,
  message,
  Popconfirm,
  List,
  Typography
} from "antd"
import {PlusOutlined, CloseOutlined} from '@ant-design/icons';
import {QuestionPo} from "../../../../types";

const zimus = ["A", "B", "C", "D", "E", "F", "G", "H"]
const initOptions = [
  {
    "label": "A选项",
    "name": "option-A"
  },
  {
    "label": "B选项",
    "name": "option-B"
  }
]

interface QuestionsProps {
  questions: QuestionPo[]
}

export default forwardRef((props: PropsWithChildren<QuestionsProps>, ref) => {
  useImperativeHandle(ref, () => ({
    sendQuestion(): QuestionPo[] {
      return questions;
    }
  }))
  const [questions, setQuestions] = useState<QuestionPo[]>(() => props.questions);
  const [drawerShow, setDrawerShow] = useState(false) // 抽屉
  const [form] = Form.useForm();
  const [editIndex, setEditIndex] = useState(-1);  // 编辑索引
  // 选项
  const [optionFields, setOptionFields] = useState<Record<"label" | "name", string>[]>([...initOptions])
  // 初始化数据
  useEffect(() => {
    if (props.questions.length) {
      setQuestions([...props.questions])
    }
  }, [props.questions])

  const columns = [
    {
      title: "主键",
      dataIndex: "id",
      width: "70px",
      render(text, r, index) {
        if (!text) return "/"
        return text
      }
    },
    {
      title: "编号",
      dataIndex: "stem",
      width: "80px",
      render(text, r, index) {
        return `第${index + 1}题`
      }
    },
    {
      title: "题目类型",
      dataIndex: "type",
      width: "100px",
      render(text) {
        if (text == 1) return "单选题"
        if (text == 2) return "多选题"
      }
    },
    {
      title: "题干",
      dataIndex: "stem",
    },
    {
      title: "题目",
      dataIndex: "options",
      render(text, r, index) {
        return <List size="small" dataSource={Object.keys(text)} renderItem={(key) => {
          return <List.Item><Typography.Text>{key}. {text[key]}</Typography.Text></List.Item>
        }
        }/>
      }
    },
    {
      title: "解析",
      dataIndex: "analysis",
    },
    {
      title: "答案",
      dataIndex: "answer",
    },
    {
      title: "操作",
      width: "160px",
      render(text, record, index) {
        const {options, ...rest} = record;
        return <>
          <Button type="link" onClick={() => {
            setEditIndex(() => index)
            setOptionFields(() => {
              return Object.keys(options).map(item => {
                rest[`option-${item}`] = options[item]
                return {
                  label: `${item}选项`,
                  name: `option-${item}`
                }
              })
            })
            setDrawerShow(() => true)
            setTimeout(() => {
              form.setFieldsValue(rest)
            })

          }
          }>编辑</Button>
          <Popconfirm title="确定要删除吗？" onConfirm={() => {
            setQuestions(qs => qs.filter((q, qi) => qi !== index))
          }}>
            <Button type="link">删除</Button>
          </Popconfirm>
        </>
      }
    }
  ]
  // 新增选项
  const addOne = () => {
    if (optionFields.length >= zimus.length) return message.error(`最多只能添加${zimus.length}个选项`)
    setOptionFields(r => {
      const zimu = zimus[r.length]
      return [...r, {
        "label": `${zimu}选项`,
        "name": `option-${zimu}`
      }];
    })
  }
  // 删除一个选项
  const removeOne = (index: number) => {
    setOptionFields(r => {
      return r.filter((a, b) => b !== index)
    })
  }
// 保存
  const save = async () => {
    await form.validateFields()
    const values = form.getFieldsValue()
    const targetValues: QuestionPo = Object.keys(values).reduce((container, key) => {
      if (key.search("option-") > -1) {
        const zimu = key.split("-")[1]
        container.options[zimu] = values[key]
        return container
      }
      return {...container, [key]: values[key]}
    }, {options: {}}) as QuestionPo
    if (editIndex > -1) { // 编辑模式
      setQuestions((qs) => {
        return qs.map((item, i) => {
          if (i === editIndex) {
            return {...item, ...targetValues}
          }
          return item
        })
      })
    } else { // 新增模式
      setQuestions(qs => ([...qs, targetValues]))
    }
    drawerClose(); // 关闭
  }

  // drawerClose
  const drawerClose = () => {
    setDrawerShow(false)
    setEditIndex(-1)
    form.resetFields()
  }


  return <>
    <Card title="试题信息" bodyStyle={{padding: 0}} extra={
      <>
        <Button type={"link"} onClick={() => {
          setDrawerShow(true)
          setOptionFields([...initOptions])
        }
        }>手动添加</Button>
        <Button type={"link"}>批量导入</Button>
      </>
    }>
      <Table<QuestionPo> columns={columns} dataSource={questions} bordered
                         rowKey={(r) => r.stem + r.answer}/>
    </Card>
    {/*创建题目*/}
    <Drawer title={`${editIndex > -1 ? "编辑" : "新建"}题目`}
            width="760"
            maskClosable={false}
            keyboard={false}
      // destroyOnClose
            onClose={() => drawerClose()}
            visible={drawerShow}
            footer={
              <div
                style={{
                  textAlign: 'right',
                }}
              >
                <Button onClick={() => drawerClose()} style={{marginRight: 8}}>
                  取消
                </Button>
                <Button type="primary" onClick={() => save()}>
                  保存
                </Button>
              </div>
            }
    >
      <Form layout="vertical" form={form}>
        <Divider orientation="left">题目信息</Divider>
        <Form.Item
          name="type"
          label="题目类型"
          rules={[{required: true, message: '请选择题目类型'}]}
          initialValue={1}
        >
          <Select placeholder="请选择题目类型">
            <Select.Option value={1}>单选题</Select.Option>
            <Select.Option value={2}>多选题</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="stem"
          label="题干"
          rules={[{required: true, message: '请输入题干'}]}
        >
          <Input.TextArea placeholder="请输入题干"/>
        </Form.Item>
        {/*选项*/}
        <Divider orientation="left">选项信息</Divider>
        {
          optionFields.map((item, index) => {
            return <Form.Item
              key={index}
              fieldKey={index}
              {...item}
              rules={[{required: true, message: `请输入${item.label}`}]}
            >
              <Input placeholder={`请输入${item.label}`}
                     addonAfter={index > 1 ? <CloseOutlined onClick={() => removeOne(index)}/> : null}/>
            </Form.Item>
          })
        }
        <Form.Item>
          <Button
            onClick={() => addOne()}
            type="dashed"
          >
            <PlusOutlined/> 新增一个选项
          </Button>
        </Form.Item>
        <Divider orientation="left">答案与解析</Divider>
        <Form.Item
          name="answer"
          label="正确答案"
          rules={[
            {required: true, message: '请输入正确答案'}, {
              pattern: /^([A-Z],)*[A-Z]$/g, message: "答案必须是大写字母，且以英文逗号分割"
            }
          ]}
        >
          <Input placeholder="请输入正确答案，多选以,号(英文逗号)分割"/>
        </Form.Item>
        <Form.Item
          name="analysis"
          label="解析"
          rules={[{required: true, message: '请输入解析'}]}
        >
          <Input.TextArea placeholder="请输入解析"/>
        </Form.Item>
      </Form>
    </Drawer>
  </>;
})
